// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Data;

namespace SnapObjects.Data
{
    internal class DataTableExporter : IDataTableExporter
    {
        private readonly DataTable _dataTable;

        public DataTableExporter(DataTable dataTable)
        {
            _dataTable = dataTable;
        }

        public string Export(bool changedOnly, DataFormat format, DataFormatSetting setting = null)
        {
            if (_dataTable.Rows.Count > 0)
            {
                var formater = DataFormaterFactory.GetWriteFormater(this.GetProperties(), format, setting);

                this.ExportRows(changedOnly, formater, setting);

                this.ExportEnd(formater);

                return formater.ToString();
            }

            return "[]";
        }

        private IDictionary<string, Type> GetProperties()
        {
            IDictionary<string, Type> properties = new Dictionary<string, Type>();

            foreach (DataColumn column in _dataTable.Columns)
            {
                properties.Add(column.ColumnName, column.DataType);
            }

            return properties;
        }

        private void ExportRows(
            bool changeOnly, IDataWriteFormater<object> formater, DataFormatSetting setting)
        {
            var entries = new DataTableModelEntryLazyReader<object>(
                _dataTable.Rows, _dataTable.Columns, changeOnly, setting);

            formater.WriteRows(entries);
        }

        private void ExportEnd(IDataWriteFormater<object> formater)
        {
            formater.WriteEnd();
        }
    }
}
